package com.baoteng.rbspy.jobs;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baoteng.rbspy.cache.LocalCacheManager;
import com.baoteng.rbspy.config.car.RbSysConfig;
import com.baoteng.rbspy.model.Model;
import com.baoteng.rbspy.model.proposal.InfoPolicy;
import com.baoteng.rbspy.model.request.proposal.QueryPolicyRequest;
import com.baoteng.rbspy.service.ProposalService;
import com.google.common.collect.Lists;

@Component
public class PolicyHolder {
	
	private static final Logger logger = LoggerFactory.getLogger(PolicyHolder.class);
	
	@Autowired
	RbSysConfig rbSysConfig;

	final List<Integer> seqNo = Lists.newArrayList(1,2,3,4,5);
	
	final static int PAGE_LIMIT = 10;
	
	@Autowired
	LocalCacheManager statusCache;
	
	@Autowired
	ProposalService proposalService;

	@Scheduled(fixedDelay = 5 * 60 * 1000)
	public void statusRefresh() {
		logger.info("PolicyHolder jobs done.refresh count:{}");
		final LocalDate _date = LocalDate.now();
		List<InfoPolicy> result = Lists.newArrayList();
		seqNo.stream().filter(i -> {
			QueryPolicyRequest request = new QueryPolicyRequest();
			request.setComCode(rbSysConfig.getComCode());
			request.setOperatorCode(rbSysConfig.getOperatorCode());
			request.setOperateDate(_date.plusDays(-5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
			request.setOperateDate2(_date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
			request.setPageSize(50);
			request.setPageNo(i);
			Model<InfoPolicy> _response = null;
			try {
				_response = proposalService.listPolicy(request);
				if (_response != null && _response.getData() != null) {
					result.addAll(_response.getData());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return _response == null || _response.getData() == null || _response.getData().isEmpty() ? true : false;
		}).findFirst().orElseGet(()->{
			if(seqNo.size()<PAGE_LIMIT) seqNo.add(seqNo.size()+1);
			return seqNo.size();
		});
		statusCache.refreshPolicyStatus(result);
		logger.info("PolicyHolder jobs done.refresh count:{}",result.size());
	}
}
